﻿using GDGeek;
using Mirror;
using MrPP.Myth;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static MrPP.Myth.Yggdrasil;

namespace MrPP.SampleGame { 

    public class BallGenerator : MonoBehaviour,IBridgeReceiver
    {
        public void Start() {
            BridgeBroadcast.Instance.addReceiver(this);
        }
        public void OnDestory() {
            BridgeBroadcast.Instance?.removeReceiver(this);
        }
        public string handle => this.longName();

        [SerializeField]
        private Transform _temp;
        [SerializeField]
        private GameObject _ballPrefab;

        private Queue<GameObject> _queue = new Queue<GameObject>();
        public void broadcast(string evt, object data)
        {

            if (evt == "fire") {
                AsgardPose ap = (AsgardPose)(data);
                var wp = Yggdrasil.Instance.getWorldPose(ap);
                var ball = Instantiate(_ballPrefab, wp.position, Quaternion.LookRotation(wp.forward, wp.up));
               
                NetworkServer.Spawn(ball);
                _queue.Enqueue(ball);
                while (_queue.Count > 6) {
                   var old = _queue.Dequeue();
                    NetworkServer.Destroy(old);
                }
            }
        }

        
        public void fireBall(Vector3 pos, Quaternion rot)
        {
            _temp.position = pos;
            _temp.rotation = rot;
            _temp.setGlobalScale(_ballPrefab.transform.lossyScale);
            WorldPose wp = new WorldPose(_temp);
            var ap = Yggdrasil.Instance.getAsgardPose(wp);//.WorldToAsgard(wp, TargetPoint.Instance.transform);
            Bridge.Instance.post(this.handle, "fire", ap);
        }
    }
}